package net.borlis.errors.providers.implementation.filebase;

import net.borlis.errors.exceptions.ExceptionKeyMaster;
import net.borlis.errors.exceptions.IExceptionKeyMaster;
import net.borlis.errors.exceptions.ServerException;
import net.borlis.errors.providers.common.IServerExceptionProcessor;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;

import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author alex@borlis.net
 */
@ApplicationScoped @LocaleFileErrors
public class LocaleFileServerExceptionProcessor implements IServerExceptionProcessor {

    @Inject
    private Logger logger;

    private PropertiesConfiguration codeKeys;

    @PostConstruct
    public void init(){
        try {
            logger.log(Level.INFO, "init local properties file based server exceptions");
            codeKeys = new PropertiesConfiguration("code_key.properties");
        } catch (ConfigurationException e) {
            logger.log(Level.SEVERE, "cannot init server exceptions properties file", e);
        }
    }

    private String getKey(String code){
        String key = codeKeys.getString(code);
        if(key==null){
            throw new IllegalArgumentException("there is no " + code + " element");
        }
        return key;
    }

    @Override
    public ServerException newServerException(String code) {
        String key = getKey(code);
        return new ServerException(new ExceptionKeyMaster(code, key));
    }

    @Override
    public ServerException newServerException(String code, Throwable cause) {
        String key = getKey(code);
        return new ServerException(new ExceptionKeyMaster(code, key), cause);
    }

    @Override
    public Set<IExceptionKeyMaster> getSupportedCodes() {
        Set<IExceptionKeyMaster> result = new HashSet<>();
        for (Iterator<String> it = codeKeys.getKeys(); it.hasNext();){
            String code = it.next();
            logger.log(Level.FINE, "adding code error message " + code + "/" + codeKeys.getString(code));
            IExceptionKeyMaster master = new ExceptionKeyMaster(code, codeKeys.getString(code));
            logger.log(Level.FINE, "added code error message " + master);
            result.add(master);
        }
        return result;
    }

}
